//
//  HonorViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/3/31.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class HonorViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource,MWPhotoBrowserDelegate {
    
    var segmentedControl: UISegmentedControl!
    var tableView: UITableView!
    
    var mark = "1"
    
    var workArray = NSMutableArray()
    var classArray = NSMutableArray()
    var teacherArray = NSMutableArray()
    
    let top = 10
    var pageIndex = 1
    
    var photoArray = NSMutableArray()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "班级荣誉"
        //1228 - 保存到本地数据进行读取
        self.workArray = getLocationData(key: honorWorkArray)
        
        InitViews()
        
        NotificationCenter.default.addObserver(self, selector: #selector(HonorViewController.showBigImage(_:)), name: NSNotification.Name(rawValue: "showBigImage"), object: nil)
    }
    
    /**
     显示大图
     
     - parameter notification:
     */
    func showBigImage(_ notification: Notification) {
        let dic: NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
        let imageUrl = dic.object(forKey: "url")
        let index = UInt(dic.object(forKey: "index") as! String)
        let array = (imageUrl as! String).components(separatedBy: "|")
        let array1 = NSMutableArray()
        array1.addObjects(from: array)
        let n = array1.count
        photoArray = NSMutableArray()
        for i in 0...n-1 {
            var url = array1.object(at: i) as! String
            url = server + url.replacingOccurrences(of: "../..", with: "")
            photoArray.add(MWPhoto.init(url: URL.init(string: url)))
            
        }
        let browser: MWPhotoBrowser = MWPhotoBrowser.init(delegate: self)
        // Set options
        browser.displayActionButton = true; // Show action button to allow sharing, copying, etc (defaults to YES)
        browser.displayNavArrows = false; // Whether to display left and right nav arrows on toolbar (defaults to NO)
        browser.displaySelectionButtons = false; // Whether selection buttons are shown on each image (defaults to NO)
        browser.zoomPhotosToFill = true; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
        browser.alwaysShowControls = false; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
        browser.enableGrid = true; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
        browser.startOnGrid = false; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
        browser.autoPlayOnAppear = false; // Auto-play first video
        
        // Customise selection images to change colours if required
        //        browser.customImageSelectedIconName = @"ImageSelected.png";
        //        browser.customImageSelectedSmallIconName = @"ImageSelectedSmall.png";
        //
        //        // Optionally set the current visible photo before displaying
        browser.setCurrentPhotoIndex(index!)
        self.navigationController?.pushViewController(browser, animated: true)
        browser.showNextPhoto(animated: true)
        browser.showPreviousPhoto(animated: true)
    }
    func numberOfPhotos(in photoBrowser: MWPhotoBrowser!) -> UInt {
        return UInt(photoArray.count)
    }
    func photoBrowser(_ photoBrowser: MWPhotoBrowser!, photoAt index: UInt) -> MWPhotoProtocol! {
        
        if index < UInt(photoArray.count) {
            
            return photoArray.object(at: Int(index)) as! MWPhotoProtocol
            
        }
        
        return nil;
    }
    
    func InitViews(){
        
        let array = ["全校荣誉","班级排行","教师排行"]
        segmentedControl = UISegmentedControl.init(items: array)
        segmentedControl.frame = CGRect(x: 30, y: 74, width: screenW - 60, height: 40)
        segmentedControl.selectedSegmentIndex = 0
        segmentedControl.tintColor = barColor
        segmentedControl.addTarget(self, action: #selector(HonorViewController.selTab), for: UIControlEvents.valueChanged)
        self.view.addSubview(segmentedControl)
        
        
        tableView = UITableView.init(frame: CGRect(x: 0, y: segmentedControl.frame.maxY + 10, width: screenW, height: screenH - segmentedControl.frame.maxY - 10))
        tableView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        self.view.addSubview(tableView)
        setUpRefresh()
        
    }
    func setUpRefresh() {
        if mark == "1" {
            
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(HonorViewController.refresh))
            tableView.footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(HonorViewController.loadMore))
            self.tableView.header.beginRefreshing()
        }else {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(HonorViewController.refresh))
            tableView.footer = nil
            self.tableView.header.beginRefreshing()
        }
        
    }
    /**
     加载更多
     */
    func loadMore() {
        
        let reachability = Reachability.forInternetConnection()
        if (reachability?.isReachable())! {
            let user = getUserPojo()
            let url = server + adminwebapppi
            pageIndex += 1
            let page: String = String(pageIndex)
            let request = requestHeader + "11</t><sch>" + user.schid + "</sch><top>5</top><pagindex>" + page + "</pagindex></channel></rss>"
            
            workArray.addObjects(from: getData(url, request: request) as [AnyObject])
            tableView.reloadData()
            
        } else {
            HYLog("网络连接：不可用")
        }

        tableView.footer.endRefreshing()
    }
    /**
     刷新数据
     t=11   全校班级荣誉列表
     XmlNode schseridxml = ndoc.SelectSingleNode("//rss/channel/sch");
     XmlNode topxml = ndoc.SelectSingleNode("//rss/channel/top");
     XmlNode pagcountxml = ndoc.SelectSingleNode("//rss/channel/pagindex");
     */
    func refresh() {
        
        //检测网路状态的变化
        let reachability = Reachability.forInternetConnection()
        if (reachability?.isReachable())! {
            HYLog("网络连接：可用")
            let user = getUserPojo()
            let url = server + adminwebapppi
            
            /**
             *  mark = "1"  全校活动
             *  mark = "2"  班级排行
             *  mark = "3"  教师排行
             */
            if mark == "1" {
                pageIndex = 1
                let page: String = String(pageIndex)
                let request = requestHeader + "11</t><sch>" + user.schid + "</sch><top>5</top><pagindex>" + page + "</pagindex></channel></rss>"
                //1228 - 本地化
                //++++++++++++++++++++++++++++++++++++++++++
//            workArray = getData(url, request: request)
                //++++++++++++++++++++++++++++++++++++++++++
                var tempArray = HttpUtils.httpPostUTF(url, with: request)
                tempArray = tempArray?.replacingOccurrences(of: "\"null\"", with: "\"\"").replacingOccurrences(of: "null", with: "\"\"").replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n").replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\t", with: " ").replacingOccurrences(of: "+", with: "%20")
                
                setLocationData(tempArray!, key: honorWorkArray)
                self.workArray = getLocationData(key: honorWorkArray)
                //++++++++++++++++++++++++++++++++++++++++++
                
                tableView.separatorStyle = UITableViewCellSeparatorStyle.none
            }else if mark == "2" {
                let request = requestHeader + "12</t><sch>" + user.schid + "</sch></channel></rss>"
                
                //1228 - 本地化
                //++++++++++++++++++++++++++++++++++++++++++
//            classArray = getData(url, request: request)
                //++++++++++++++++++++++++++++++++++++++++++
                
                var tempArray = HttpUtils.httpPostUTF(url, with: request)
                tempArray = tempArray?.replacingOccurrences(of: "\"null\"", with: "\"\"").replacingOccurrences(of: "null", with: "\"\"").replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n").replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\t", with: " ").replacingOccurrences(of: "+", with: "%20")
                
                setLocationData(tempArray!, key: honorClassArray)
                self.classArray = getLocationData(key: honorClassArray)
                
                //++++++++++++++++++++++++++++++++++++++++++
                
                tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
            }else if mark == "3" {
                let request = requestHeader + "13</t><sch>" + user.schid + "</sch></channel></rss>"
                
                //1228 - 本地化
                //++++++++++++++++++++++++++++++++++++++++++
//                teacherArray = getData(url, request: request)
                //++++++++++++++++++++++++++++++++++++++++++
                
                var tempArray = HttpUtils.httpPostUTF(url, with: request)
                tempArray = tempArray?.replacingOccurrences(of: "\"null\"", with: "\"\"").replacingOccurrences(of: "null", with: "\"\"").replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n").replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\t", with: " ").replacingOccurrences(of: "+", with: "%20")
                
                setLocationData(tempArray!, key: honorTeacherArray)
                self.teacherArray = getLocationData(key: honorTeacherArray)
                
                //++++++++++++++++++++++++++++++++++++++++++
                
                tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
            }
            
            tableView.reloadData()
        } else {
            HYLog("网络连接：不可用")
        }
        
        tableView.header.endRefreshing()
        
    }
    /**
     选项切换
     */
    func selTab() {
        let n = segmentedControl.selectedSegmentIndex
        switch n {
        case 0:
            mark = "1"
            self.workArray = getLocationData(key: honorWorkArray)
            
            break
        case 1:
            mark = "2"
            self.classArray = getLocationData(key: honorClassArray)
            
            break
        case 2:
            mark = "3"
            self.teacherArray = getLocationData(key: honorTeacherArray)
            
            break
        default:
            break
        }
        
        self.tableView.reloadData()
        setUpRefresh()
        
    }
    
    /**
     高度
     
     - parameter tableView: tableview
     - parameter indexPath: item
     
     - returns: 高度
     */
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if mark == "1" {
            if (indexPath as NSIndexPath).row < workArray.count {
                let dic = workArray[indexPath.row] as! JSON
                let imageUrl = dic["HonorUrl"].stringValue
                var title = dic["Honor"].stringValue
                title = title.removingPercentEncoding!
                var height: CGFloat = 0.0
                if imageUrl.characters.count == 0 {
                    
                    height = 0.0
                    
                }else {
                    
                    let array = imageUrl.components(separatedBy: "|")
                    
                    height = getPhotoCollectionHeight(array as NSArray)
                }
                /// 头像，间隔，上下间隔，时间，图片等，内容
                let cellHeight: CGFloat = 10.0 + 20.0 + 30.0 + height + getLabelHeight(title, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 40)
                return cellHeight
            }else{
                return 0
            }
        }else if mark == "2" {
            return 60
        }else {
            return 60
        }
    }
    /**
     多少行
     
     - parameter tableView: tableview
     - parameter section:
     
     - returns: 行数
     */
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if mark == "1" {
            return workArray.count
        }else if mark == "2" {
            return classArray.count
        }else {
            return teacherArray.count
        }
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if mark == "1" {
            
            if (indexPath as NSIndexPath).row < workArray.count {
                let cellIdentifier = "HonorTableViewCellIdentifier";
                let dic = workArray[indexPath.row] as! JSON
                let cell = HonorTableViewCell(dictionary: dic, reuseIdentifier: cellIdentifier)
                cell.selectionStyle = UITableViewCellSelectionStyle.none;
                return cell
            }else{
                return UITableViewCell()
            }
            
            
        }else if mark == "2" {
            let cellIdentifier = "ClassSendTableViewCellIdentifier";
            
            let cell: ClassSendTableViewCell = ClassSendTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < classArray.count {
                let dic = classArray[indexPath.row] as! JSON
                let classname = dic["classname"].stringValue
                let count = dic["classcon"].stringValue
                
                cell.classname.text = classname
                cell.count.text = "发布：" + count
            }
            
            return cell
            
        }else {
            let cellIdentifier = "ClassCountTableViewCellIdentifier";
            
            let cell: StudentListTableViewCell = StudentListTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < teacherArray.count {
                let dic = teacherArray[indexPath.row] as! JSON
                let teaname = dic["teaname"].stringValue
                let count = dic["usersendcon"].stringValue
                var photo = dic["teaphoto"].stringValue
                photo = photo.replacingOccurrences(of: "../..", with: "").replacingOccurrences(of: "../", with: "/view/")
                photo = server + photo
                cell.userTx.sd_setImage(with: URL.init(string: photo), placeholderImage: UIImage.init(named: "touxiangm"))
                cell.userName.text = teaname
                cell.count.text = "发布：" + count
                
            }
            return cell
            
        }
        
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
